package com.leyou.cart.interceptors;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 拦截当前请求
     * 从token中获取userid
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
//        获取token
            String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
//        获取payload
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
//        获取userid
            Long userId = payload.getUserInfo().getId();
//         放入当前线程的threadlocal
            UserHolder.setUserId(userId);
            return true;//放行
        }catch(Exception e){
            log.error("没有获取到当前用户的id");
            e.printStackTrace();
            return false;//
        }

    }

    /**
     * 从threadlocal中删除数据
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUserId();
    }
}
